<?php
// $Id: question.pages.inc,v 1.2.2.2 2011/04/01 20:51:55 goba Exp $

/**
 * @file
 * User page callbacks for the ntuts_question module.
 */

/**
 * This function is responsible for generating a question form.
 * There are several cases that have to be handled, including:
 *   - replies to nodes
 *   - respecting access permissions ('access question', 'post question', etc.)
 *
 * The node or question that is being replied to must appear above the question
 * form to provide the user context while authoring the question.
 *
 * @param $node
 *   Every question belongs to a node. This is that node.
 * 
 *
 * @return
 *   The rendered the new question form.
 */
function question_reply($node) {

  $output = '';

  //if (user_access('access questions')) {
    if (user_access('access content')) {
        $output .= node_view($node, FALSE, TRUE);
    }
    $output .= question_node_form_box(array('nid' => $node->nid), t('Đặt câu hỏi về '. $node->title));
    $output .= ntuts_question_list_node_question($node);
/*  }
  else {
    drupal_set_message(t('You are not authorized to view questions.'), 'error');
    drupal_goto("node/$node->nid");
  }
*/
  return $output;
}

function ntuts_question_list_node_question($node)
{
  $path = drupal_get_path('module', 'ntuts_question');
  drupal_add_css($path .'/ntuts_question.css');
  drupal_add_js($path .'/ntuts_question.js', 'module');
  $output = '';
  if($node->nid)
  {
    $result = pager_query('SELECT DISTINCT(q.qid),q.question ,u.uid, q.timestamp, q.qid, u.name, q.nid FROM {ntuts_question} q INNER JOIN {users} u ON u.uid = q.uid WHERE q.status = 1 AND q.nid = %d ORDER BY q.timestamp DESC', 15, 0, NULL, $node->nid);
	
    while ($question = db_fetch_object($result)) {
      $num_answer = db_result(db_query('SELECT count(aid) as num FROM {ntuts_answer} WHERE qid = %d AND status = 1', $question->qid));
      $user = user_load($question->uid);
				if ($user->picture && file_exists($user->picture)) {
					$picture = theme('imagecache', 'avt50', $user->picture);
				} else {
					$picture = theme('imagecache', 'avt50', variable_get('user_picture_default', ''));
				}
				$picture = l($picture, "user/$user->uid", array('title' => $user->name, 'html' => TRUE), NULL, NULL, FALSE, true);
        $output .=  '<div class="ntuts_question">'
                      .'<div class="qitem clearfix">'
												 .'<div class="picture">'.$picture.'</div>'
                        .'<div class="question">'
                          .'<div>'.theme('username', $user).' hỏi: </div>'
						  .'<div class="qtitle">'.l($question->question, "node/{$node->nid}/question/{$question->qid}", array('attributes' => array('class' => 'q-link', 'id' => "question_$question->qid"))).'</div>'
                          .'<div>'.format_date($question->timestamp, 'small').' - <span id="num_answer_'.$question->qid.'">'. intval($num_answer).'</span> trả lời</div>'
                        .'</div>'
                      .'</div>'
                      .'<div class="aitem"></div>'
                    .'</div>';
		$output .= '<div class="indented question_'.$question->qid.'" style="display:none">';
		$output .= '</div>';
    }
    $output .= theme('pager', NULL, 15, 0);
  }
  return $output;
}

function ajax_list_answer_of_question($qid) {

  //if reply to question $qid
  if (isset($_POST['uid']) && isset($_POST['msg'])){
	global $user;
	if (isset($_POST['aid'])){//update answer
		$answer_arr = array('answer' => $_POST['msg'], 'qid' => $qid, 'uid' => $user->uid, 'aid' => $_POST['aid']);
	}
	else{//add answer
		$answer_arr = array('answer' => $_POST['msg'], 'qid' => $qid, 'uid' => $user->uid);
	}
	$aid = answer_save($answer_arr);
	if (!$aid)
		return;
	$results = db_query('SELECT a.*, u.uid, u.name FROM {ntuts_answer} a INNER JOIN {users} u ON u.uid = a.uid WHERE a.status = 1 AND a.aid = %d', $aid);
	if (!$results)
		return;
	$output = answer_html(db_fetch_object($results));
	drupal_json(array('status' => 1, 'qid' => $qid, 'data' => $output));
	return;
  }
  
  //else get answers for question $qid
  $output = '';
  $result = pager_query('SELECT a.*, u.uid, u.name FROM {ntuts_answer} a INNER JOIN {users} u ON u.uid = a.uid WHERE a.status = 1 AND a.qid = %d ORDER BY a.timestamp ASC', 15, 0, NULL, $qid);
  $countAnswer = 0;
  while ($answer = db_fetch_object($result)) {
    $output .= answer_html($answer);
	/*
	$rowStyle = "odd";
	if( $countAnswer % 2 == 1 )
		$rowStyle = "even";
	$user2 = user_load($answer->uid);
	if ($user2->picture && file_exists($user2->picture)) {
		$picture2 = theme('imagecache', 'avt50', $user2->picture);
	} else {
		$picture2 = theme('imagecache', 'avt50', variable_get('user_picture_default', ''));
	}
	$picture2 = l($picture2, "user/$user2->uid", array('title' => $user2->name, 'html' => TRUE), NULL, NULL, FALSE, true);
	$output .=  '<div class="aitem ans-'.$answer->aid.'">'
					.'<div class="aicontent">'.$answer->answer.'</div>'
					.'<div class="aiuser clearfix">'
						.'<div class="picture">'.$picture2.'</div>'
						.'<div class="question">'
							.'<div>'.theme('username', $user2).' trả lời lúc '.format_date($answer->timestamp, 'small').'</div>'
						.'</div>'
						.'<div class="links">
							<ul class="links"><li class=""><a href="javascript:void(0);" onclick="deleteAnswer('.$answer->aid.');return false;" class="">delete</a></li>
							<li class="comment_edit"><a href="javascript:void(0);">edit</a></li>
							<li class="comment_reply"><a href="javascript:void(0);" class="">reply</a></li>
							</ul>
						</div>'
					.'</div>'
				.'</div>';
				
	$countAnswer++;
	*/
  }
  $output .=  drupal_get_form('ajax_answer_question_form', array('qid' => $qid));
  drupal_json(array('status' => 0, 'qid' => $qid,'data' => $output));
  //return $output;
}

function answer_html($answer){
	global $user;
	$user2 = user_load($answer->uid);
	if ($user2->picture && file_exists($user2->picture)) {
		$picture = theme('imagecache', 'avt50', $user2->picture);
	} else {
		$picture = theme('imagecache', 'avt50', variable_get('user_picture_default', ''));
	}
	$edit_html = '';
	
	//display edit, delete only if owner or administrator
	if ($user->uid >0 && ($user->uid == $user2->uid || $user->uid==1 || in_array('administrator', array_values($user->roles))))
		$edit_html = '<div class="links">
						<ul class="links"><li class=""><a href="answer/'.$answer->aid.'/delete" onclick="return deleteAnswer('.$answer->aid.');" class="">delete</a></li>
						<li class="comment_edit"><a href="javascript:void(0);">edit</a></li>
						</ul>
					  </div>';
	
	$picture = l($picture, "user/$user2->uid", array('title' => $user2->name, 'html' => TRUE), NULL, NULL, FALSE, true);
	$output .=  '<div class="aitem ans-'.$answer->aid.'">'
					.'<div class="aicontent">'.$answer->answer.'</div>'
					.'<div class="aiuser clearfix">'
						.'<div class="picture">'.$picture.'</div>'
						.'<div class="question">'
							.'<div>'.theme('username', $user2).' trả lời lúc '.format_date($answer->timestamp, 'small').'</div>'
						.'</div>'
						.$edit_html
					.'</div>'
				.'</div>';
	return $output;
}

function ajax_delete_answer($aid){
	global $user;
	$results = db_query('SELECT a.*, u.uid, u.name FROM {ntuts_answer} a INNER JOIN {users} u ON u.uid = a.uid WHERE a.status = 1 AND a.aid = %d', $aid);
	if (!$results){
		drupal_json(array('status' => 0, 'text' => 'no answer with id: '.$aid));
		return;
	}
	$answer = db_fetch_object($results);
	//only owner or admin can delete
	if ($user->uid >0 && ($user->uid == $answer->uid || $user->uid==1 || in_array('administrator', array_values($user->roles)))){
		db_query('DELETE FROM {ntuts_answer} WHERE aid = %d', $aid);
		drupal_json(array('status' => 1, 'text' => 'delete successfully id:'.$aid));
		return;
	}
	drupal_json(array('status' => 0, 'text' => 'not enough permission to delete id: '.$aid));
}

function list_aswer_of_question($qid) {

  $question = db_fetch_object(db_query('SELECT * FROM {ntuts_question} WHERE qid = %d AND status = 1', $qid));
  $output = '<div class="traloi">';
  if($question)
  {
    $node = node_load($question->nid);
   // if (user_access('access questions') ) {
      if (user_access('access content')) {
          $output .= node_view($node, FALSE, TRUE);
      }
      $output .= ntuts_question_show_question($question);
      $output .= ntuts_question_list_question_answer($question);
      $output .= drupal_get_form('answer_question_form', array('qid' => $question->qid, 'nid' => $question->nid));
      
  /*  }
    else {
      drupal_set_message(t('You are not authorized to view questions.'), 'error');
      drupal_goto("node/$node->nid");
    }*/
  }
  $output .= '</div>';
  return $output;
}
function ntuts_question_show_question($question)
{
  $user = user_load($question->uid);
  $output = '<h3>'.$question->question.'</h3><div class="qitem clearfix">';
  $output .= theme('user_picture', $user);
  $output .= '<div class="question">'
              .'<div>'.theme('username', $user).' hỏi lúc '.format_date($question->timestamp, 'small').'</div>'
              .'</div></div>';
  return $output;
}
function ntuts_question_list_question_answer($question)
{
  //drupal_add_js(drupal_get_path('module', 'ntuts_question') .'/ntuts_question.js', 'module');
  $output = '';
  if($question->qid)
  {
    $result = pager_query('SELECT a.*, u.uid, u.name FROM {ntuts_answer} a INNER JOIN {users} u ON u.uid = a.uid WHERE a.status = 1 AND a.qid = %d ORDER BY a.timestamp DESC', 15, 0, NULL, $question->qid);

    while ($answer = db_fetch_object($result)) {
      $user = user_load($answer->uid);
			if ($user->picture && file_exists($user->picture)) {
				$picture = theme('imagecache', 'avt50', $user->picture);
			} else {
				$picture = theme('imagecache', 'avt50', variable_get('user_picture_default', ''));
			}
			$picture = l($picture, "user/$user->uid", array('title' => $user->name, 'html' => TRUE), NULL, NULL, FALSE, true);
        $output .=  '<div class="aitem">'
                      .'<div class="aicontent">'.$answer->answer.'</div>'
                      .'<div class="aiuser clearfix">'
                      .'<div class="picture">'.$picture.'</div>'
                      .'<div class="question">'
                      .'<div>'.theme('username', $user).' trả lời lúc '.format_date($question->timestamp, 'small').'</div>'
                      .'</div></div></div>';
    }
    $output .= theme('pager', NULL, 15, 0);
  }
  return $output;
}